package arkanoid.components;

import java.awt.Color;

import arkanoid.components.ball.Ball;
import arkanoid.scenes.Level;

import com.uqbar.vainilla.DeltaState;
import com.uqbar.vainilla.GameComponent;
import com.uqbar.vainilla.appearances.Rectangle;
import com.uqbar.vainilla.colissions.CollisionDetector;

public class Brick extends GameComponent<Level> {

	private int width  = 97;
	private int height = 20;
	private int endurance;
	
	public Brick(int x, int y, int endurance) {
		this.setAppearance(new Rectangle(Color.getHSBColor(0.8f + endurance * 0.1f, 0.56f, 0.75f), this.getWidth(), this.getHeight()));
		this.setX(x);
		this.setY(y);
		this.setEndurance(endurance);
	}
	
	public void update(DeltaState deltaState) {
		for (Ball ball : this.getScene().getBalls()) {
			if (this.collidesAgainstBall(ball)) {
				if (this.collidesFromUp(ball)) {
					ball.setY(ball.getY() - ball.getRatio());
					ball.setVersorJ(-ball.getVersorJ());
				}
				if (this.collidesFromDown(ball)) {
					ball.setY(ball.getY() + ball.getRatio());
					ball.setVersorJ(-ball.getVersorJ());
				}
				if (this.collidesFromLeft(ball)) {
					ball.setX(ball.getX() - ball.getRatio());
					ball.setVersorI(-ball.getVersorI());
				}
				if (this.collidesFromRight(ball)) {
					ball.setX(ball.getX() + ball.getRatio());
					ball.setVersorI(-ball.getVersorI());
				}
				this.setEndurance(this.getEndurance() - 1);
				if (this.getEndurance() == 0) {
					this.getScene().removeBrick(this);
					this.getScene().dropPowerUp(this.getX() + this.getWidth() / 2, this.getY() + this.getHeight() / 2);
				}
			}
		}
	}
	
	private boolean collidesFromUp(Ball ball) {
		return !(ball.getY() + ball.getRatio() >= this.getY() + this.getHeight());
	}
	
	private boolean collidesFromDown(Ball ball) {
		return !(ball.getY() + ball.getRatio() <= this.getY());
	}

	private boolean collidesFromLeft(Ball ball) {
		return !(ball.getX() + ball.getRatio() >= this.getX() + this.getWidth());
	}

	private boolean collidesFromRight(Ball ball) {
		return !(ball.getX() + ball.getRatio() <= this.getX());
	}
	
	private boolean collidesAgainstBall(Ball ball) {
		return CollisionDetector.INSTANCE.collidesCircleAgainstRect(
				ball.getX(), ball.getY(), ball.getRatio(),
				this.getX(), this.getY(), this.getWidth(), this.getHeight()
				);
//		return ball.getY() + ball.getDiameter() / 2 >= this.getY() && ball.getY() <= this.getY() + this.getHeight() ||
//				ball.getX() + ball.getDiameter() / 2 >= this.getX() && ball.getX() <= this.getX() + this.getWidth();
	}
	
	

	public int getWidth() {
		return width;
	}

	public int getHeight() {
		return height;
	}

	public int getEndurance() {
		return endurance;
	}

	public void setEndurance(int endurance) {
		this.endurance = endurance;
	}
}
